<template>
  <div class="user-list">
    <!-- 过滤卡片 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="demo-form-inline">
        <el-form-item label="广告标题">
          <el-input
              v-model="filterForm.title"
              placeholder="请输入广告标题"
              clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="状态">
          <el-select
              v-model="filterForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
          >
            <el-option label="全部" value=""></el-option>
            <el-option label="正常" :value="1"></el-option>
            <el-option label="封禁" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchUsers" :loading="loading">
            <i class="el-icon-search"></i> 查询
          </el-button>
          <el-button @click="resetFilter">
            <i class="el-icon-refresh"></i> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 广告创意列表-->
    <el-card>
      <div slot="header" class="clearfix">
        <span>广告创意列表</span>
        <el-button style="float: right; margin-top: -5px" type="primary" @click="handleAdd">
          <i class="el-icon-plus"></i> 新增
        </el-button>
      </div>

      <el-table :data="creativesList" border fit style="width: 100%">
        <el-table-column prop="creativeId" label="编号" ></el-table-column>
        <el-table-column prop="campaignName" label="计划名称"></el-table-column>
        <el-table-column prop="adTypeDesc" label="类型"></el-table-column>
        <el-table-column prop="title" label="标题"></el-table-column>
<!--        <el-table-column prop="description" label="描述"></el-table-column>-->
        <el-table-column prop="createTime" label="创建时间" >
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tooltip :content="row.status === 1 ? '正常' : '封禁'" placement="top">
              <el-switch
                  v-model="row.status"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  :active-value="1"
                  :inactive-value="0"
                  @change="newStatus => handleSwitchChange(row, newStatus)">
              </el-switch>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="{ row }">
            <el-link type="primary" @click="handleView(row)">查看</el-link>
            <el-divider direction="vertical" />
            <el-link type="danger" @click="handleDelete(row)">删除</el-link>
            <el-divider direction="vertical" />
            <el-link type="success" @click="handleEdit(row)">编辑</el-link>
          </template>
        </el-table-column>
      </el-table>

      <!--      分页-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
        title="广告创意信息"
        v-model="dialogVisible"
        width="60%"
        center
    >
      <el-form :model="form" label-width="120px" ref="formRef">

        <el-form-item label="广告计划名称" prop="campaignName">
          <el-select
              v-model="form.campaignId"
              placeholder="选择广告计划名称"
              :disabled="isViewMode"
              clearable
          >
            <el-option
                v-for="item in campaignOptions"
                :key="item.campaign_id"
                :label="item.campaign_name"
                :value="item.campaign_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="广告类型" prop="adTypeCode">
          <el-select
              v-model="form.adTypeCode"
              placeholder="选择广告类型"
              :disabled="isViewMode"
              clearable
          >
            <el-option
                v-for="item in adTypeOptions"
                :key="item.dict_code"
                :label="item.description"
                :value="item.dict_code"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="标题" prop="title">
          <el-input
              v-model="form.title"
              placeholder="请输入标题"
              :disabled="isViewMode"
          ></el-input>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
              type="textarea"
              v-model="form.description"
              placeholder="请输入描述"
              :disabled="isViewMode"
              rows="4"
          ></el-input>
        </el-form-item>

        <el-form-item label="媒体URL" prop="mediaUrl">
          <el-input
              v-model="form.mediaUrl"
              placeholder="请输入媒体URL"
              :disabled="isViewMode"
          ></el-input>
        </el-form-item>

        <el-form-item label="点击URL" prop="clickUrl">
          <el-input
              v-model="form.clickUrl"
              placeholder="请输入点击URL"
              :disabled="isViewMode"
          ></el-input>
        </el-form-item>

        <el-form-item label="展示顺序" prop="displaySequence">
          <el-input
              v-model.number="form.displaySequence"
              placeholder="请输入展示顺序"
              :disabled="isViewMode"
          ></el-input>
        </el-form-item>

        <el-form-item label="点击次数" v-if="isViewMode">
          <el-input
              v-model="form.clickCount"
              placeholder="点击次数"
              :disabled="true"
          ></el-input>
        </el-form-item>

        <el-form-item label="曝光次数" v-if="isViewMode">
          <el-input
              v-model="form.impressionCount"
              placeholder="曝光次数"
              :disabled="true"
          ></el-input>
        </el-form-item>

        <el-form-item label="转化次数" v-if="isViewMode">
          <el-input
              v-model="form.conversionCount"
              placeholder="转化次数"
              :disabled="true"
          ></el-input>
        </el-form-item>

        <el-form-item label="创建时间" v-if="isViewMode">
          <template #default>
            {{ formatDate(form.createTime) }}
          </template>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-switch
              :disabled="isViewMode"
              v-model="form.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
              @change="changeStatus"
          >
          </el-switch>
        </el-form-item>
      </el-form>

      <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogVisible = false">{{ isViewMode ? '关闭' : '取消'}}</el-button>
      <el-button type="primary" @click="handleSave" v-if="!isViewMode">确定</el-button>
    </span>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import axios from '@/utils/request';
export default {
  name: 'creativesList',
  data() {
    return {
      adTypeOptions: [],
      campaignOptions:[],
      filterForm: {
        title: '',
        status: ''
      },
      // 弹窗状态
      dialogVisible: false,
      loading: true,
      creativesList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 表单数据（新增/编辑用）
      form: {
        campaignsStatus:'', //广告计划状态
        creativeId: 5,
        campaignId: 3,
        adTypeCode: 1,
        adType: "ad_type",
        title: "东南亚旅游",
        description: "暑期特惠，东南亚5国10日游",
        mediaUrl: "https://example.com/ads/sea_tour.jpg",
        clickUrl: 'aa',
        displaySequence: 1,
        status: 1,
        impressionCount: 1340,
        clickCount: 180,
        conversionCount: 36,
        createTime: "2025-06-01",
        campaignName: "旅游季推广",
        adTypeDesc: "图片广告"
      }
    }
  },
  mounted() {
    this.getAdList();
    this.loadCampaigns();
    this.loadAdType();
  },
  methods: {
    //广告计划列表
    loadCampaigns() {
      try {
        axios.get('/adCampaigns/dropdown').then(response =>{
          if (response.data.code === 200) {
            this.campaignOptions = response.data.data;
          } else {
            this.$message.error('获取广告计划列表失败');
          }
        })
      } catch (error) {
        this.$message.error('网络异常，获取广告计划列表失败');
      }
    },
    //广告类型列表
    loadAdType() {
      try {
        axios.get('/dict/dropdown').then(response =>{
          if (response.data.code === 200) {
            this.adTypeOptions = response.data.data;
          } else {
            this.$message.error('获取广告类型失败');
          }
        })
      } catch (error) {
        this.$message.error('网络异常，获取广告类型失败');
      }
    },
    // 获取列表
    getAdList() {
      this.loading = false;
      axios.get('/adCreatives/page', {
        params: {
          title: this.filterForm.title,
          status: this.filterForm.status,
          current: this.currentPage,
          size: this.pageSize
        }
      }).then(response => {
        if (response.data.code === 200) {
          this.creativesList = response.data.data.records;
          this.total = response.data.data.total;
        } else {
          this.$message.error(response.data.message || '获取列表失败');
        }
      })
    },

    // 搜索
    searchUsers() {
      this.currentPage = 1;
      this.getAdList();
    },

    // 重置过滤条件
    resetFilter() {
      this.filterForm = {
        companyName: '',
        status: ''
      };
      this.currentPage = 1;
      this.getAdList();
    },

    // 处理分页大小变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.getAdList();
    },

    // 处理当前页变化
    handleCurrentChange(page) {
      this.currentPage = page;
      this.getAdList();
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },
    // 新增
    handleAdd() {
      this.dialogVisible = true
      this.form = {
        creativeId: null,
        campaignId: 1,
        campaignsStatus:3,
        adTypeCode: '',
        title: '',
        description: '',
        mediaUrl: '',
        clickUrl: '',
        displaySequence: 0,
        status: 1,
        impressionCount: 0,
        clickCount: 0,
        conversionCount: 0,
        createTime: '',
        campaignName: '',
        adTypeDesc: ''
      }
      this.isViewMode = false
    },

    // 编辑
    handleEdit(row) {
      this.dialogVisible = true
      this.isViewMode = false
      this.form = {...row}
    },

    //查看
    handleView(row){
      this.dialogVisible = true
      this.isViewMode = true;
      this.form = {...row}
      console.log(this.form)
    },

    // 处理删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete('/adCreatives/delete',{
          params:{
            creativeId: row.creativeId
          }
        }).then( () =>{
          const index = this.creativesList.findIndex(item => item.creativeId === row.creativeId)
          if (index !== -1) {
            this.creativesList.splice(index, 1)
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    changeStatus(){
      if(this.form.campaignsStatus != 3){
        this.form.status = this.form.status === 1 ? 0 : 1;
        this.$message.error('该计划未开启');
      }
    },

    // 保存（新增/编辑）
    handleSave() {

      // 发送请求
      axios.post('/adCreatives/saveOrUpdate', this.form,)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success(this.form.creativeId ? '修改成功' : '添加成功');
              this.dialogVisible = false;
              // 刷新列表
              this.handleCurrentChange(this.currentPage);
              this.dialogVisible = false;
            } else {
              this.$message.error(response.data.message || '操作失败，请重试');
            }
          })
    },

    // 状态切换处理函数
    handleSwitchChange(ad, newStatus) {
      if(ad.campaignsStatus != 3){
        ad.status = ad.status === 1 ? 0 : 1;
        this.$message.error('该计划未开启');
      }else {
        const action = newStatus === 0 ? '禁用' : '启用';
        const statusText = newStatus === 0 ? '禁用' : '正常';
        this.$confirm(`确定要${action}吗?`, '操作确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios.post(`/adCreatives/updateStatus?creativeId=${ad.creativeId}&status=${newStatus}`).then(response => {
            if (response.data.code == 200) {
              this.$message.success(`状态已更新为: ${statusText}`);
            } else {
              ad.status = ad.status === 1 ? 0 : 1;
              this.$message.error('状态更新失败: ' + response.data.message);
            }
          }).catch(error => {
            ad.status = ad.status === 1 ? 0 : 1;
            this.$message.error('请求失败: ' + error.message);
          });
        }).catch(() => {
          ad.status = ad.status === 1 ? 0 : 1;
          this.$message.info('操作已取消');
        });

      }

    }
  }
}
</script>

<style scoped>
.user-list {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

</style>

